<?php
namespace app\api\controller\xiservice;

use app\common\controller\xiservice\XiserviceApi;
use app\common\model\xiservice\Collect as CollectModel;
use app\common\model\xiservice\Service;
use think\Db;
/**
 * 收藏模块
 */
class Collect extends XiserviceApi
{
    protected $noNeedLogin = [];
    protected $noNeedRight = ['*'];



    /**
     * @ApiTitle (用户收藏列表)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.collect/list)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="object", sample="{'id':'int','name':'string','image':'string','bargain':'int','saleprice':'float','basicnums':'int','salenums':'int'}", description="返回数据")
     */
    public function list() {
        $key = $this->request->request('keyword');
        $list = CollectModel::with(['service'=>function($query)use($key){
                        $query->where('name','like','%'.$key.'%')->withField('id,name,image,images,bargain,saleprice,basicnums,salenums');
                 }])
                ->where('user_id',$this->auth->id)
                ->paginate();
        $this->success('查询成功',$list);
    }

     /**
     * @ApiTitle (用户收藏/取消收藏操作)
     * @ApiMethod (GET)
     * @ApiRoute (/api/xiservice.collect/set)
     * @ApiHeaders (name=token, type=string, description="Token")
     * @ApiParams   (name="service_id", type="integer", description="服务id")
     * @ApiReturnParams   (name="code", type="integer", required=true, sample="0")
     * @ApiReturnParams   (name="msg", type="string", required=true, sample="返回成功")
     * @ApiReturnParams   (name="data", type="integer", description="返回数据")
     */
    public function set() {
       
        $serviceId = $this->request->request('service_id');
        $service =  Service::where('id',$serviceId)->where('status',1)->find();
        if(!$service){
            $this->error('参数错误!',[]);
        }
        $collect =  CollectModel::where('user_id',$this->auth->id)
                                ->where('service_id',$serviceId)
                                ->find();
        if($collect){
             $res =  CollectModel::where('id',$collect['id'])->delete();
             $this->success('已取消收藏',0);
        }else{
             $data['user_id'] = $this->auth->id;
             $data['service_id'] = $serviceId;
             $data['createtime'] = time();
             $res =  CollectModel::insertGetId($data);
             $this->success('收藏成功',1);
        }
        
    }   

}